<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>扫码demo</title>
    <script src="./html5-qrcode.min.js" type="text/javascript"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .render_container {
            position: fixed;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            display: none;

            background-color: black;
        }
    </style>
</head>
<body>
    <button id="button">扫码</button>
    <p id="text"></p>
    <div class="render_container" id="render_container">
        <div id="reader"></div>
    </div>
</body>
<script>
    const textDom = document.getElementById('text')

    function setText(str) {
        textDom.textContent = str
    }

    const readerDom = document.getElementById('render_container')
    function showScanBox(visible = true) {
        readerDom.style.display = visible ? 'block' : 'none'
    }

    const button = document.getElementById('button')
    button.addEventListener('click', async function () {
        const text = await useCameras()
        setText(text)
    })

    function useCameras() {
      return new Promise(async (resolve, reject) => {
        try {
          /**
           * devices would be an array of objects of type:
           * { id: "id", label: "label" }
           */
          const devices = await Html5Qrcode.getCameras()
          if(devices.length) {
            let cameraId
            if(devices[1]) {
                cameraId = devices[1].id
            } else {
              cameraId = devices[0].id
            }

            showScanBox()
            const html5QrCode = new Html5Qrcode(/* element id */ "reader");
            await html5QrCode.start(
              cameraId,
              {
                fps: 10,    // Optional, frame per seconds for qr code scanning
                qrbox: { width: 250, height: 250 }  // Optional, if you want bounded box UI
              },
              (decodedText, decodedResult) => {
                html5QrCode.stop()
                showScanBox(false)
                // do something when code is read
                resolve(decodedText)
              },
              (errorMessage) => {
                // parse error, ignore it.
              })
          } else {
            reject('未检测到摄像头')
          }
        } catch (err) {
          reject(err.name + ": " + err.message)
        }
      })
    }
</script>
</html>